﻿using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace LaoLuo.IO
{
    /// <summary>
    /// provide ext methods related to file, directory
    /// </summary>
    public static class FileExtensions
    {
        /// <summary>
        /// 获取指定路径中的文件
        /// </summary>
        /// <param name="directory"></param>
        /// <returns></returns>
        public static string[] GetFiles(this string directory)
        {
            return Directory.GetFiles(directory);
        }

        /// <summary>
        /// 获取指定路径中的文件, 不包括路径
        /// </summary>
        /// <param name="directory"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetFilesWithoutPath(this string directory)
        {
            return Directory.GetFiles(directory).Select(item => item.GetFileName());
        }

        #region extension name

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="file">文件名</param>
        /// <returns>文件的扩展名</returns>
        public static string GetFileExtension(this string file)
        {
            return Path.GetExtension(file);
        }

        /// <summary>
        /// get files with specified extension in the specified directory
        /// </summary>
        /// <param name="directory">the directory from which to retrieve files</param>
        /// <param name="extension">the extensions using which to filter files</param>
        /// <returns></returns>
        public static IEnumerable<string> GetFilesByExtension(this string directory, params string[] extension)
        {
            return directory.GetFilesByExtension((IEnumerable<string>)extension);
        }

        public static IEnumerable<string> GetFilesByExtension(this string directory, IEnumerable<string> extension)
        {
            if (!Directory.Exists(directory))
            {
                return Enumerable.Empty<string>();
            }

            var files = Directory.GetFiles(directory);

            return files.WhereExtensionIn(extension);
        }

        public static IEnumerable<string> WhereExtensionIn(this IEnumerable<string> file, params string[] extension)
        {
            return file.WhereExtensionIn(extension.AsEnumerable());
        }

        public static IEnumerable<string> WhereExtensionIn(this IEnumerable<string> file, IEnumerable<string> extension)
        {
            return file.Where(i => extension.Contains(i.GetFileExtension()));
        }

        public static string GetFileNameWithoutExtension(this string file)
        {
            return Path.GetFileNameWithoutExtension(file);
        }

        #endregion

        public static string GetFileName(this string path)
        {
            return Path.GetFileName(path);
        }
    }
}
